<?php

class Mem
{
    private string $type = 'Memcached';
    private mixed $m;
    private int $time = 0;
    private string $error = '';
    public string $debug = 'true';

    public function __construct()
    {
        if (!class_exists($this->type)) {
            $this->error = 'No ' . $this->type;
            return false;
        } else {
            $this->m = new $this->type;
        }
    }

    public function addServer(array $array)
    {
        $this->m->addServers($array);
    }

    public function s($key, $value = '', $time = NULL)
    {
        $number = func_num_args();
        if ($number == 1) {
            return $this->get($key);
        } elseif ($number >= 2) {
            if ($value === NULL) {
                // delete
                $this->delete($key);
            } else {
                // set
                $this->set($key, $value, $time);
            }
        }
    }

    private function get($key)
    {
        $result = $this->m->get($key);
        if ($this->debug == 'true') {
            if ($this->m->getResultCode() != 0) {
                return false;
            }
        }
        return $result;
    }

    private function set($key, $value, $time = NULL)
    {
        if ($time === NULL) {
            $time = $this->time;
        }
        $this->m->set($key, $value, $time);
        if ($this->debug == 'true') {
            if ($this->m->getResultCode() != 0) {
                return false;
            }
        }
    }

    private function delete($key)
    {
        $this->m->delete($key);
    }

    public function getError()
    {
        if ($this->error) {
            return $this->error;
        } else {
            return $this->m->getResultMessage();
        }
    }
}